package cn.neusoft.yuejian307.Fragment;

import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioGroup;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.view.SimpleDraweeView;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import cn.neusoft.yuejian307.Fragment.insidefragment.FragmentActivity;
import cn.neusoft.yuejian307.Fragment.insidefragment.FragmentMaster;
import cn.neusoft.yuejian307.Fragment.insidefragment.FragmentRace;
import cn.neusoft.yuejian307.R;



public class FragmentThree extends Fragment {
    private RadioGroup radioGroup;
    private FragmentManager manager;
    private FragmentTransaction transaction;
    private Fragment mTab01;
    private Fragment mTab02;
    private Fragment mTab03;


    SimpleDraweeView[] simpleDraweeViews;

    int currentItem;
    private ScheduledExecutorService executor;
    ViewPager viewPager;
    View view;



    String[] imageUris = {
            "http://39.106.51.191/yuejian/Public/images/userpics/one.jpg",
            "http://39.106.51.191/yuejian/Public/images/userpics/two.jpg",
            "http://39.106.51.191/yuejian/Public/images/userpics/three.jpg",
            "http://39.106.51.191/yuejian/Public/images/userpics/four.jpg",
            "http://39.106.51.191/yuejian/Public/images/userpics/five.jpg",
            "http://39.106.51.191/yuejian/Public/images/userpics/6.jpg",
            "http://39.106.51.191/yuejian/Public/images/userpics/7.jpg",
            "http://39.106.51.191/yuejian/Public/images/userpics/8.jpg",
            "http://39.106.51.191/yuejian/Public/images/userpics/9.jpg"
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater , ViewGroup container , Bundle savedInstanceState)
    {
        view = inflater.inflate(R.layout.fragment_three, null) ;
        int size = initSize();
        initTextViews(size);
        initViewPager();
        init();
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        radioGroup = (RadioGroup) view.findViewById(R.id.main_tab_RadioGroup);
        manager = getChildFragmentManager();
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId){
                    case R.id.radio_activity:
                        mTab01 = new FragmentActivity();
                        replace(mTab01);
                        break;
                    case R.id.radio_master:
                        mTab02 = new FragmentMaster();
                        replace(mTab02);
                        break;
                    case R.id.radio_race:
                        mTab03 = new FragmentRace();
                        replace(mTab03);
                        break;
                }

            }
        });

        radioGroup.check(R.id.radio_activity);


    }

    private void  replace(Fragment fragment){

        transaction=manager.beginTransaction();
        transaction.replace(R.id.id_content,fragment);
        transaction.commit();


    }


    public FragmentThree() {
    }



    private void init(){
        Fresco.initialize(getActivity());
    }

    @Override
    public void onResume() {
        super.onResume();

        startAutoScroll(); // activity激活时候自动播放
    }

    @Override
    public void onPause() {
        super.onPause();

        stopAutoScroll(); // activity暂停时候停止自动播放
    }

    private void startAutoScroll() {
        stopAutoScroll();

        executor = Executors.newSingleThreadScheduledExecutor();
        Runnable command = new Runnable() {
            @Override
            public void run() {
                selectNextItem();
            }

            private void selectNextItem() {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        viewPager.setCurrentItem(++currentItem);
                    }
                });
            }
        };
        int delay = 2;
        int period = 2;
        TimeUnit timeUnit = TimeUnit.SECONDS;
        executor.scheduleAtFixedRate(command, delay, period, timeUnit);
    }

    private void stopAutoScroll() {
        if (executor != null) {
            executor.shutdownNow();
        }
    }



    private void initViewPager() {
        viewPager = (ViewPager) view.findViewById(R.id.viewPage);

        viewPager.setAdapter(new PagerAdapter() {
            @Override
            public int getCount() {
                return Integer.MAX_VALUE; // 取一个大数字
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {

                SimpleDraweeView t = simpleDraweeViews[position % simpleDraweeViews.length];
                container.addView(t);

                Uri uri = Uri.parse(imageUris[position % simpleDraweeViews.length]);
                t.setImageURI(uri);

                return t;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {

                container.removeView((View) object);
            }
        });

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                currentItem = position;

                startAutoScroll(); // 手动切换完成后恢复自动播放
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        currentItem = imageUris.length * 1000000; // 取一个中间的大数字, 防止接近边界
        viewPager.setCurrentItem(currentItem);
    }

    private void initTextViews(int size) {
        SimpleDraweeView[] tvs = new SimpleDraweeView[size];
        init();
        for (int i = 0; i < tvs.length; i++) {
            tvs[i] = new SimpleDraweeView(getActivity());
            tvs[i].getHierarchy().setPlaceholderImage(R.mipmap.ic_launcher);

            ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            tvs[i].setLayoutParams(layoutParams);
            simpleDraweeViews = tvs;
        }
    }

    private int initSize() {
        int size;
        if (imageUris.length > 3) {
            size = imageUris.length;
        } else {
            size = imageUris.length * 2; // 小于3个时候, 需要扩大一倍, 防止出错
        }
        return size;
    }
}